package com.zzyl.nursing.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.domain.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 入住Service业务层处理
 *
 * @author mr.wu
 * @date 2025-05-17
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private IBedService bedService;

    @Autowired
    private IElderService elderService;

    @Autowired
    private IContractService contractService;

    @Autowired
    private ICheckInConfigService checkInConfigService;


    /**
     * 申请入住
     *
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void apply(CheckInApplyDto dto) {
        //老人的身份证号
        String cardNo = dto.getCheckInElderDto().getIdCardNo();

        //1. 判断老人是否已入住 select count(*) from check_in where id_card_no=? and status=0
        Long countCheckIn = this.lambdaQuery().eq(CheckIn::getIdCardNo, cardNo)
                .eq(CheckIn::getStatus, 0).count();
        if (countCheckIn > 0) {
            throw new RuntimeException("老人已入住过");
        }

        //2. 判断符合要求的床位是否已存在 select * from bed where id=? and bed_status=0
        Long bedId = dto.getCheckInConfigDto().getBedId();
        Bed bed = bedService.lambdaQuery().eq(Bed::getId, bedId)
                .eq(Bed::getBedStatus, 0).one();
        if (bed == null) {
            throw new RuntimeException("床位不符合要求");
        }

        //3. 更新床位状态为已入住  update bed set bed_status=1 where id=?
        Bed bedDB = new Bed();
        bedDB.setId(bedId);
        bedDB.setBedStatus(1);//已入住
        boolean bedResult = bedService.updateById(bedDB);
//        boolean bedResult =  bedService.lambdaUpdate().eq(Bed::getId,bed)
//                .set(Bed::getBedStatus,1)
//                .update();
        if (!bedResult) {
            throw new RuntimeException("更新床位失败");
        }

        //4. 新增或更新老人
        //查询老人信息 select * from elder where id_card_no=?
        Elder elder = saveElder(dto, cardNo, bedId, bed);

        //5. 新增签约信息（合同信息）
        saveContract(dto, elder);

        //6. 新增入住信息
        CheckIn checkIn = saveCheckIn(dto, elder, cardNo, bed);

        //7. 新增入住配置
        saveCheckInConfig(dto, checkIn);
    }


    /**
     * 新增入住配置
     *
     * @param dto
     * @param checkIn
     */
    private void saveCheckInConfig(CheckInApplyDto dto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        //拷贝入住配置信息
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());//入住信息id
        boolean resultCheckInfoConfig = checkInConfigService.save(checkInConfig);
        if (!resultCheckInfoConfig) {
            throw new RuntimeException("新增入住配置信息失败");
        }
    }

    /**
     * 新增入住信息
     *
     * @param dto
     * @param elder
     * @param cardNo
     * @param bed
     * @return
     */
    @NotNull
    private CheckIn saveCheckIn(CheckInApplyDto dto, Elder elder, String cardNo, Bed bed) {
        CheckIn checkIn = new CheckIn();
        //拷贝入住信息
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkIn);
        checkIn.setElderName(elder.getName());//老人姓名
        checkIn.setElderId(elder.getId());//老人ID
        checkIn.setIdCardNo(cardNo);//老人身份证号
        checkIn.setBedNumber(bed.getBedNumber());//床位编号
        checkIn.setStatus(0);//已入住
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));//家属信息的JSON字符串
        boolean resultCheckIn = this.save(checkIn);
        if (!resultCheckIn) {
            throw new RuntimeException("新增入住信息失败");
        }
        return checkIn;
    }

    /**
     * 新增合同信息
     *
     * @param dto
     * @param elder
     */
    private void saveContract(CheckInApplyDto dto, Elder elder) {

    }

    /**
     * 新增老人基础信息
     *
     * @param dto
     * @param cardNo
     * @param bedId
     * @param bed
     * @return
     */
    @NotNull
    private Elder saveElder(CheckInApplyDto dto, String cardNo, Long bedId, Bed bed) {
        Elder elder = elderService.lambdaQuery().eq(Elder::getIdCardNo, cardNo).one();
        if (elder == null) {
            elder = new Elder();
        }
        //拷贝老人信息
        BeanUtils.copyProperties(dto.getCheckInElderDto(), elder);
        elder.setBedId(bedId);//床位ID
        elder.setBedNumber(bed.getBedNumber());//床位编号
        elder.setStatus(4);//入住中
        boolean resultElder = elderService.save(elder);
        if (!resultElder) {
            throw new RuntimeException("新增老人信息失败");
        }
        return elder;
    }

    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        // 1. 查询入住信息
        CheckIn checkInfo = this.getById(id);
        if (checkInfo == null) {
            throw new RuntimeException("入住记录不存在");
        }

        // 2. 查询老人信息
        Elder elder = elderService.getById(checkInfo.getElderId());
        if (elder == null) {
            throw new RuntimeException("老人信息不存在");
        }

        // 3. 查询合同
        Contract contract = contractService.lambdaQuery()
                .eq(Contract::getElderId, elder.getId())
                .one();

        // 4. 查询入住配置
        CheckInConfig checkInConfig = checkInConfigService.lambdaQuery()
                .eq(CheckInConfig::getCheckInId, id)
                .one();

        // 5. 转为家属列表
        List<ElderFamilyVo> familyList = Collections.emptyList();
        if (StringUtils.isNotEmpty(checkInfo.getRemark())) {
            JSONArray objects = JSON.parseArray(checkInfo.getRemark());
            familyList = objects.toJavaList(ElderFamilyVo.class);
        }

        // 6. 整合数据返回
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();

        // 初始化老人信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        // 设置家属信息
        checkInDetailVo.setElderFamilyVoList(familyList);

        // 设置入住配置（记得你也需要补全这部分）
        if (checkInConfig != null) {
            CheckInConfigVo configVo = new CheckInConfigVo();
            BeanUtils.copyProperties(configVo, checkInConfig);
            checkInDetailVo.setCheckInConfigVo(configVo);
        }

        // 设置合同信息（记得你也需要补全这部分）
        if (contract != null) {
            CheckInContractVo contractVo = new CheckInContractVo();
            BeanUtils.copyProperties(contract, contractVo);
            checkInDetailVo.setContract(contractVo);
        }

        return checkInDetailVo;
    }
}


